package com.shipwe.loans.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.shipwe.adapter.ShipweOnItemChildClickListener
import com.shipwe.loans.MyApps
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentStepAuthOcrBinding
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityAuthSteps
import com.shipwe.loans.ui.activity.ActivityCameraOcr
import com.shipwe.loans.ui.adapter.AuthStepOcrTypeAdapter
import com.shipwe.loans.ui.presenter.UploadPresenter
import com.shipwe.loans.ui.view.IUploadView
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.dialog.PhotoDialog
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.imgcovert.ImageConvert
import com.shipwe.loans.utils.log.ShipweLogger
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:40
 * @Annotation：认证流程 - 身份证、护照、驾驶证
 */
class FragmentStepAuthOcr(): ShipweFragment(), IUploadView {
    lateinit var binding: FragmentStepAuthOcrBinding
    private var presenter: UploadPresenter? = null

    private var stepItem: JSONObject? = null

    private val typeTitleList = arrayListOf(
        "${MyApps.app.getString(R.string.step_ocr_idcard)},IDCARD",
        "${MyApps.app.getString(R.string.step_ocr_passport)},PASSPORT",
        "${MyApps.app.getString(R.string.step_ocr_drving_license)},DRIVING"
    )
    private val typeImgList = arrayListOf(
        R.drawable.auth_ocr_id_card,
        R.drawable.auth_ocr_passport,
        R.drawable.auth_ocr_drving_license
    )

    private var typeAdapter: AuthStepOcrTypeAdapter? = null
    private var selectItem: JSONObject? = null
    private var photoDialog: PhotoDialog? = null

    //是否是正面
    private var isFront = true
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""

    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentStepAuthOcrBinding.inflate(inflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        if (stepItem != null){
            binding.authStepTitle.text = stepItem!!.optString("showTitle")
        }

        initAuthStepOcrTypeListView()
    }

    override fun initShipweListener() {
        //idcard 正面
        binding.ocrIdCardView.idCardFront.setOnClickListener { onAuthStepOcrImageClickListener(it) }
        //idcard 反面
        binding.ocrIdCardView.idCardBack.setOnClickListener { onAuthStepOcrImageClickListener(it) }
        //驾驶证 正面
        binding.ocrDrvingLicenseView.drvingLicenseFront.setOnClickListener { onAuthStepOcrImageClickListener(it) }
        //驾驶证 反面
        binding.ocrDrvingLicenseView.drvingLicenseBack.setOnClickListener { onAuthStepOcrImageClickListener(it) }
        //护照 正面
        binding.ocrPassportView.passportView.setOnClickListener { onAuthStepOcrImageClickListener(it) }

        //提交
        binding.ocrSubmit.setOnClickListener {
            if (selectItem == null){
                return@setOnClickListener
            }
            val ocrType = selectItem!!.optString("ocrType")
            if (!isSibAllowSubmit()){
                showErrorTipsDialog(getString(R.string.dialog_tips_submit_error),ocrType)
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.SHIPWE_API_OCR_INFO_PATH)
                put("cardType",ocrType)//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
            }
            params.put("cardImgUrl",imgFrontUrl)//证件图片正面
            if (imgBackUrl.isNotEmpty()){
                params.put("cardBackImgUrl",imgBackUrl)//证件图片反面
            }

            val act = getAct() as ActivityAuthSteps
            act.onAuthStepsSubmitAction(params)

            appEventPointRequestAction(String.format(AppEventPointType.CLICK.SHIPWE_CLICK_STEP_OCR_XX_NEXT,ocrType),"")
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        ShipweLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showShipweLoading(isTOuchOut = false, isCancel = false)
                        presenter!!.submitUploadImageAction(localPath)
                    }
                }
            } else {
                ShipweLogger.e("No media selected")
            }
        }
    }

    override fun initShipweData() {
        presenter = UploadPresenter(this)
        val typeList = arrayListOf<JSONObject>()
        for (i in 0..<typeTitleList.size){
            val item = JSONObject()
            item.put("ocrTitle",typeTitleList[i].split(",")[0])
            item.put("ocrType",typeTitleList[i].split(",")[1])
            item.put("imgResource",typeImgList[i])
            if (i == 0){
                item.put("isSelect",true)
                selectItem = item
            } else {
                item.put("isSelect",false)
            }
            typeList.add(item)
        }
        typeAdapter!!.data = typeList
        //设置显示Ocr类型
        showAuthStepOcrTypeViews()
    }

    /**
     * 初始化View
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initAuthStepOcrTypeListView(){
//        binding.ocrTypeListView.setHasFixedSize(true)
        binding.ocrTypeListView.isNestedScrollingEnabled = false
        binding.ocrTypeListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.ocrTypeListView.layoutManager = layoutManager
//        val topDecoration = AppDensityUtil.dp2px(6f)
//        binding.ocrTypeListView.addItemDecoration(GridSpacingItemDecoration(3,topDecoration,false))
        typeAdapter = AuthStepOcrTypeAdapter(binding.ocrTypeListView)
        binding.ocrTypeListView.adapter = typeAdapter!!
        binding.ocrTypeListView.itemAnimator = DefaultItemAnimator()
        typeAdapter!!.setOnItemChildClickListener(ShipweOnItemChildClickListener { _, _, position ->
            val item = typeAdapter!!.getItem(position)
            if (item.optBoolean("isSelect", false)) {
                return@ShipweOnItemChildClickListener
            }
            selectItem = item
            for (i in 0..<typeAdapter!!.itemCount) {
                val obj = typeAdapter!!.getItem(i)
                obj.put("isSelect", false)
                if (i == position) {
                    obj.put("isSelect", true)
                }
            }
            typeAdapter!!.notifyDataSetChanged()

            //设置显示Ocr类型
            showAuthStepOcrTypeViews()
        })
    }

    /**
     * Ocr拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                ShipweLogger.e(">>>>>>onActivityResult: data = " + result.data)
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                showUploadImageSuccess(imgLocalPath,imgUrl)
            }
        }
    }

    /**
     * 显示Ocr类型
     */
    private fun showAuthStepOcrTypeViews(){
        if (selectItem == null){
            return
        }
        binding.ocrTypeTitle.text = selectItem!!.optString("ocrTitle")

        imgFrontUrl = ""
        imgBackUrl = ""
        binding.ocrIdCardView.idCardView.visibility = View.GONE
        binding.ocrIdCardView.idCardFrontImage.setImageResource(R.drawable.auth_ocr_front)
        binding.ocrIdCardView.idCardBackImage.setImageResource(R.drawable.auth_ocr_back)
        binding.ocrDrvingLicenseView.drvingLicenseView.visibility = View.GONE
        binding.ocrDrvingLicenseView.drvingLicenseFrontImage.setImageResource(R.drawable.auth_ocr_front)
        binding.ocrDrvingLicenseView.drvingLicenseBackImage.setImageResource(R.drawable.auth_ocr_back)
        binding.ocrPassportView.passportView.visibility = View.GONE
        binding.ocrPassportView.passportImage.setImageResource(R.drawable.auth_ocr_front)
        when(selectItem!!.optString("ocrType")){
            "DRIVING" -> {//驾驶证
                binding.ocrDrvingLicenseView.drvingLicenseView.visibility = View.VISIBLE
            }
            "PASSPORT" -> {//护照
                binding.ocrPassportView.passportView.visibility = View.VISIBLE
            }
            else -> {//身份证
                binding.ocrIdCardView.idCardView.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 点击选择图片
     */
    private fun onAuthStepOcrImageClickListener(v: View){
        when(v.id){
            binding.ocrIdCardView.idCardFront.id -> {//身份证 正面
                isFront = true
                showAuthStepOcrPhotoDialog("IdCard Front")
            }
            binding.ocrIdCardView.idCardBack.id -> {//身份证 反面
                isFront = false
                showAuthStepOcrPhotoDialog("IdCard Back")
            }
            binding.ocrDrvingLicenseView.drvingLicenseFront.id -> {//驾驶证 正面
                isFront = true
                showAuthStepOcrPhotoDialog("DriverLicense Front")
            }
            binding.ocrDrvingLicenseView.drvingLicenseBack.id -> {//驾驶证 反面
                isFront = false
                showAuthStepOcrPhotoDialog("DriverLicense Back")
            }
            binding.ocrPassportView.passportView.id -> {//护照
                showAuthStepOcrPhotoDialog("Passport")
            }
        }
    }

    /**
     * 相机、相册
     */
    private fun showAuthStepOcrPhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = PhotoDialog(requireContext(),object : PhotoDialog.IDialogCallback{
                override fun openCamera() {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CAMERA,eventRemark)
                    openAuthStepOceCamera()
                }
                override fun openAlbum() {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_ALBUM,eventRemark)
                    openAuthStepOceAlbum()
                }
            })
            photoDialog!!.setCancelable(true)
            photoDialog!!.setCanceledOnTouchOutside(true)
        }
        photoDialog!!.setEventRemark(eventRemark)
        photoDialog!!.show()
    }

    /**
     * 打开相册
     */
    private fun openAuthStepOceAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 打开相机
     */
    private fun openAuthStepOceCamera(){
        if (selectItem != null){
            takePhotoResultLauncher.launch(Intent(context, ActivityCameraOcr::class.java))
        }
    }

    /**
     * 图片上传成功
     */
    override fun showUploadImageSuccess(imgPath: String, imgUrl: String) {
        if (selectItem == null){
            return
        }
        when(selectItem!!.optString("ocrType")){
            "DRIVING" -> {//驾驶证
                if (isFront){
                    imgFrontUrl = imgUrl
                    AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.ocrDrvingLicenseView.drvingLicenseFrontImage,imgPath)
                } else {
                    imgBackUrl = imgUrl
                    AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.ocrDrvingLicenseView.drvingLicenseBackImage,imgPath)
                }
            }
            "PASSPORT" -> {//护照
                imgFrontUrl = imgUrl
                AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.ocrPassportView.passportImage,imgPath)
            }
            else -> {//身份证
                if (isFront){
                    imgFrontUrl = imgUrl
                    AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.ocrIdCardView.idCardFrontImage,imgPath)
                } else {
                    imgBackUrl = imgUrl
                    AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.ocrIdCardView.idCardBackImage,imgPath)
                }
            }
        }
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isSibAllowSubmit(): Boolean{
        if (imgFrontUrl.isEmpty()){
            return false
        }
        val ocrType = selectItem!!.optString("ocrType")
        if (imgBackUrl.isEmpty() && (ocrType == "DRIVING" || ocrType == "IDCARD")){
            return false
        }
        return true
    }

    override fun onStart() {
        super.onStart()
        if (stepItem != null){
            appEventPointRequestAction(String.format(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_OCR_XX_START,stepItem!!.optString("stepTitle")),"")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stepItem != null){
            appEventPointRequestAction(String.format(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_OCR_XX_END,stepItem!!.optString("stepTitle")),"")
        }
    }
}